package cn.raven.system.service.impl;

import cn.raven.basic.query.BaseQuery;
import cn.raven.basic.service.impl.BaseServiceImpl;
import cn.raven.basic.utils.PageList;
import cn.raven.system.domain.Role;
import cn.raven.system.mapper.MenuMapper;
import cn.raven.system.mapper.PermissionMapper;
import cn.raven.system.mapper.RoleMapper;
import cn.raven.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Raven
 * @since 2022-07-11
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void add(Role role) {
        roleMapper.add(role);
        initAddIntermediateTable(role);
    }

    @Override
    public void update(Role role) {
        //先修改，因为可能会修改
        roleMapper.update(role);
        initDelIntermediateTable(role.getId());
        initAddIntermediateTable(role);
    }
    
    /** 
    * @Title: initDelIntermediateTable
    * @Description: 删除menu和permission中间表数据
    * @Author: king
    * @Version: 1.0
    * @Date:  2022/7/13 11:07  
    * @Parameters: [role]
    * @Return void
      */
    private void initDelIntermediateTable(Long id) {
            //先删除中间表数据
            roleMapper.delRoleMenu(id);
            roleMapper.delRolePermission(id);
    }
    /**
    * @Title: initAddIntermediateTable
    * @Description: 添加menu和permission中间表数据
    * @Author: king
    * @Version: 1.0
    * @Date:  2022/7/13 11:07
    * @Parameters: [role]
    * @Return void
      */
    private void initAddIntermediateTable(Role role) {
        if (role.getMenus() != null) {
            //在添加中间表数据
            roleMapper.addRoleMenu(role.getId(),role.getMenus());
            roleMapper.addRolePermission(role.getId(),role.getPermissions());
        }
    }

    @Override
    public void del(Long id) {
        initDelIntermediateTable(id);
        roleMapper.del(id);

    }

    @Override
    public PageList<Role> queryData(BaseQuery baseQuery) {
        List<Role> roles = roleMapper.queryData(baseQuery);
        for (Role role :roles){
            role.setOwnMenus(menuMapper.findByMenu(role.getId()));
            role.setOwnPermissions(permissionMapper.findByPermission(role.getId()));
        }
        Integer count = roleMapper.queryCount(baseQuery);
        return new PageList<>(count,roles);
    }
}
